<template>
  <div class="traction-container">
    <div v-for="(track, index) in tracks" :key="index" :ref="(el) => setTrackRef(el, index)" class="traction-track">
      <div
        v-for="(car, carIndex) in track.cars"
        :key="car.id"
        :ref="(el) => setCarRef(el, index, carIndex)"
        :style="getCarStyle(car)"
        class="traction-car"
      >
        <div class="car-body">
          <div class="car-platform">
            <div class="car-body-mask">{{ car.name }}</div>
            <!-- 添加小车元素，始终存在但通过display控制显示/隐藏 -->
            <div class="small-car" style="display: none">
              <span class="car-id">{{ car.id }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import {inject, reactive, ref} from 'vue';

/**
 * 从Vue的依赖注入系统中获取'remSizeTran'的值
 *
 * 该函数使用Vue的inject API来获取由祖先组件通过provide提供的'remSizeTran'值
 * 常用于组件需要获取全局配置或跨层级组件通信的场景
 *
 * @returns {*} 返回注入的'remSizeTran'值，具体类型取决于提供者提供的类型
 */
const remSize = inject('remSizeTran');

// 配置参数
const CONFIG = reactive({
  TRACK_WIDTH: 10 * remSize.value + 20, // 轨道宽度
  TRACK_HEIGHT: 70 * remSize.value, // 轨道高度
  CAR_WIDTH: 10 * remSize.value, // 牵车宽度
  CAR_HEIGHT: 5 * remSize.value, // 牵车高度
  ANIMATION_DURATION: 2000, // 动画持续时间
  MIN_DISTANCE: 100, // 最小安全距离
  TRACK_COLOR: 'rgba(64, 224, 208, 0.3)', // 轨道颜色
  TRACK_WIDTH: 4, // 轨道宽度
  PADDING: 20 // 轨道内边距
});

// 轨道数据
const tracks = ref([
  { id: 'track1', cars: [], path: null },
  { id: 'track2', cars: [], path: null }
  // { id: 'track3', cars: [], path: null }
]);

// 轨道和牵车的引用
const trackRefs = ref([]);
const carRefs = ref([]);

// 设置轨道引用
const setTrackRef = (el, index) => {
  if (el) {
    trackRefs.value[index] = el;
  }
};

// 设置牵车引用
const setCarRef = (el, trackIndex, carIndex) => {
  if (el) {
    if (!carRefs.value[trackIndex]) {
      carRefs.value[trackIndex] = [];
    }
    carRefs.value[trackIndex][carIndex] = el;
  }
};

// 获取牵车样式
const getCarStyle = (car) => {
  return {
    // 新增：向左偏移10px
    transform: `translateX(calc(-17%)) translateY(${car.position}px)`,
    transition: car.isMoving ? `transform ${CONFIG.ANIMATION_DURATION}ms ease-in-out` : 'none'
  };
};

// 计算实际位置
const calculateActualPosition = (elementId, containerHeight) => {
  // 获取目标元素
  const targetElement = document.getElementById(elementId);
  if (!targetElement) {
    console.warn(`Target element with id ${elementId} not found`);
    return 0;
  }

  // 获取目标元素的位置信息
  const targetRect = targetElement.getBoundingClientRect();
  const containerRect = document.querySelector('.traction-container').getBoundingClientRect();
  const trackRect = document.querySelector('.traction-track').getBoundingClientRect();

  // 计算目标元素相对于轨道的位置
  const targetTop = targetRect.top - trackRect.top;
  const targetHeight = targetRect.height;

  // 计算牵车应该停止的位置（垂直居中对齐）
  // 考虑轨道的内边距和牵车高度
  const trackPadding = 20; // 与 CSS 中的 padding 保持一致
  const carPosition = targetTop + targetHeight / 2 - CONFIG.CAR_HEIGHT / 2 - trackPadding;

  // 确保位置在有效范围内，并留出边距
  const minPosition = trackPadding;
  const maxPosition = trackRect.height - CONFIG.CAR_HEIGHT - trackPadding;
  return Math.max(minPosition, Math.min(carPosition, maxPosition));
};

// 检查位置是否安全
const isPositionSafe = (trackIndex, position, carId) => {
  const track = tracks.value[trackIndex];
  const car = track.cars.find((c) => c.id === carId);
  if (!car) return false;

  // 获取当前轨道上所有其他牵车
  const otherCars = track.cars.filter((c) => c.id !== carId);

  // 检查是否与其他牵车重叠
  return !otherCars.some((otherCar) => {
    // 计算两个牵车之间的距离
    const distance = Math.abs(otherCar.position - position);
    // 考虑牵车高度和最小安全距离
    const minRequiredDistance = CONFIG.CAR_HEIGHT + CONFIG.MIN_DISTANCE;
    return distance < minRequiredDistance;
  });
};

// 绘制垂直移动轨迹
const drawVerticalPath = (trackIndex, startY, endY) => {
  const track = tracks.value[trackIndex];
  const trackElement = trackRefs.value[trackIndex];
  if (!trackElement) return;

  // 清除旧的轨迹
  if (track.path) {
    track.path.remove();
  }

  // 创建新的轨迹元素
  const path = document.createElement('div');
  path.className = 'vertical-path';
  path.style.position = 'absolute';
  path.style.left = '50%';
  path.style.transform = 'translateX(-50%)';
  path.style.top = `${Math.min(startY, endY)}px`;
  path.style.width = `${CONFIG.TRACK_WIDTH}px`;
  path.style.height = `${Math.abs(endY - startY)}px`;
  path.style.backgroundColor = CONFIG.TRACK_COLOR;
  path.style.borderRadius = '2px';
  path.style.zIndex = '1';

  trackElement.appendChild(path);
  track.path = path;
};

// 清除垂直移动轨迹
const clearVerticalPath = (trackIndex) => {
  const track = tracks.value[trackIndex];
  if (track.path) {
    track.path.remove();
    track.path = null;
  }
};

// 移动牵车
const moveCar = async (trackIndex, carId, targetElementId, isCarryingCar = false) => {
  const track = tracks.value[trackIndex];
  const car = track.cars.find((c) => c.id === carId);

  if (!car) return false;

  // 获取轨道元素
  const trackElement = trackRefs.value[trackIndex];
  if (!trackElement) {
    console.warn('Track element not found');
    return false;
  }

  // 获取目标元素
  const targetElement = document.getElementById(targetElementId);
  if (!targetElement) {
    console.warn(`Target element with id ${targetElementId} not found`);
    return false;
  }

  // 计算目标位置
  const containerHeight = trackElement.offsetHeight;
  const actualPosition = calculateActualPosition(targetElementId, containerHeight);

  // 检查位置是否安全
  // if (!isPositionSafe(trackIndex, actualPosition, carId)) {
  //     console.warn('Position is not safe for car movement')
  //     return false
  // }

  return new Promise((resolve) => {
    const carElement = carRefs.value[trackIndex][track.cars.indexOf(car)];
    if (!carElement) {
      resolve(false);
      return;
    }

    // 设置移动状态
    car.isMoving = true;
    car.position = actualPosition;

    // 如果正在携带小车，显示小车样式
    if (isCarryingCar) {
      const smallCar = carElement.querySelector('.small-car');
      if (smallCar) {
        smallCar.style.display = 'flex';
      }
    } else {
      // 如果不携带小车，隐藏小车样式
      const smallCar = carElement.querySelector('.small-car');
      if (smallCar) {
        smallCar.style.display = 'none';
      }
    }

    // 监听动画完成
    const handleAnimationEnd = () => {
      carElement.removeEventListener('transitionend', handleAnimationEnd);
      car.isMoving = false;

      // 额外等待一小段时间确保完全稳定
      setTimeout(() => {
        resolve(true);
      }, 200);
    };

    carElement.addEventListener('transitionend', handleAnimationEnd);

    // 设置超时保护
    setTimeout(() => {
      carElement.removeEventListener('transitionend', handleAnimationEnd);
      car.isMoving = false;
      resolve(true);
    }, CONFIG.ANIMATION_DURATION + 500);
  });
};

// 初始化牵车
const initializeCars = (trackIndex, carsData) => {
  if (trackIndex >= 0 && trackIndex < tracks.value.length) {
    const track = tracks.value[trackIndex];

    // 最多2台牵车
    const carsToInitialize = carsData.slice(0, 2);

    // 计算每台牵车的初始位置
    const positions = carsToInitialize.map((car, index) => {
      const targetId = car.position;
      if (targetId) {
        // 计算目标元素的实际位置
        const trackElement = trackRefs.value[trackIndex];
        const containerHeight = trackElement ? trackElement.offsetHeight : CONFIG.TRACK_HEIGHT;
        return calculateActualPosition(targetId, containerHeight);
      }
      // 没有目标元素时，默认放顶部或底部
      return index === 0 ? CONFIG.CAR_HEIGHT / 2 : CONFIG.TRACK_HEIGHT - CONFIG.CAR_HEIGHT;
    });

    track.cars = carsToInitialize.map((car, index) => ({
      ...car,
      position: positions[index],
      isMoving: false
    }));
  }
};

// 添加牵车
const addCar = (trackIndex, carData) => {
  if (trackIndex >= 0 && trackIndex < tracks.value.length) {
    const track = tracks.value[trackIndex];

    // 检查轨道上是否已经有最大数量的牵车
    if (track.cars.length >= 2) {
      console.warn('Track already has maximum number of cars');
      return false;
    }

    // 找到安全的位置
    let safePosition = 0;
    if (track.cars.length > 0) {
      // 如果轨道上已有牵车，将新牵车放在最上方或最下方
      const existingCar = track.cars[0];
      safePosition = existingCar.position > CONFIG.TRACK_HEIGHT / 2 ? 0 : CONFIG.TRACK_HEIGHT - CONFIG.CAR_HEIGHT;
    }

    track.cars.push({
      ...carData,
      position: safePosition,
      isMoving: false
    });
    return true;
  }
  return false;
};

// 移除牵车
const removeCar = (trackIndex, carId) => {
  if (trackIndex >= 0 && trackIndex < tracks.value.length) {
    const track = tracks.value[trackIndex];
    track.cars = track.cars.filter((car) => car.id !== carId);
  }
};

// 暴露方法
defineExpose({
  moveCar,
  initializeCars,
  addCar,
  removeCar
});
</script>

<style scoped>
.traction-container {
  width: 100%;
  height: 100%;
  position: relative;
  display: flex;
  justify-content: space-around;
  align-items: center;
}

.traction-track {
  width: v-bind('CONFIG.TRACK_WIDTH + "px"');
  height: v-bind('CONFIG.TRACK_HEIGHT + "px"');
  /* background: #2c3e50; */
  border-radius: 8px;
  position: relative;
  overflow: visible;
  padding: 20px 0; /* 保持上下内边距 */
  box-sizing: border-box; /* 确保内边距计入总高度 */
}

.traction-car {
  width: v-bind('CONFIG.CAR_WIDTH + "px"');
  height: v-bind('CONFIG.CAR_HEIGHT + "px"');
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  z-index: 2;
  display: flex;
  align-items: center;
  justify-content: center;
  will-change: transform; /* 优化动画性能 */
}

.car-body {
  width: 100%;
  height: 100%;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  /* background-image: url('@/assets/tg.png');
  background-size: 100% 100%;
  background-position: center;
  background-repeat: no-repeat; */
}

.car-platform {
  width: 100%;
  height: 100%;
  background: #18a58a;
  /* background-image: url('@/assets/tg.png'); */
  background-size: 100% 100%;
  background-position: center;
  background-repeat: no-repeat;
  border: 2px solid #81d63b; /* 金色边框 */
  border-radius: 6px;
  position: relative;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1.3rem;
  font-weight: bold;
  /* color: #2c2c2c; */
  color: #e0e0e0;
}

.car-platform::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 4px;
  background: rgba(255, 255, 255, 0.3);
  border-radius: 6px 6px 0 0;
}

.car-platform::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 4px;
  background: rgba(0, 0, 0, 0.1);
  border-radius: 0 0 6px 6px;
}

.traction-car.moving .car-platform {
  background: #ffd700; /* 移动时稍微亮一点 */
  transition: background-color 0.3s ease;
  box-shadow: 0 6px 12px rgba(0, 0, 0, 0.3);
}

.small-car {
  width: 100%;
  height: 50%;
  background: url('@/assets/cts.png') center no-repeat !important;
  background-size: 100% 100% !important;

  display: flex;
  align-items: center;
  justify-content: center;
}

.car-id {
  color: rgba(255, 255, 255, 0.9);
  font-size: 10px;
  font-weight: 600;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
}

/* .small-car::before,
.small-car::after {
    content: '';
    position: absolute;
    width: 12px;
    height: 12px;
    background: rgba(0, 0, 0, 0.8);
    border: 2px solid rgba(0, 0, 0, 0.9);
    border-radius: 50%;
    bottom: -4px;
} */

/* .small-car::before {
    left: 15px;
}

.small-car::after {
    right: 15px;
} */
</style>
